import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Dome1 {
    public static void main(String[] args) throws SQLException {
        /*
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号: ");
        int id = scanner.nextInt();
        System.out.println("请输入姓名: ");
        String name = scanner.next();
        */
        //1.先创建DataSource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java109?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("111111");
        //2.建立和数据库服务器之间的连接
        Connection connection = dataSource.getConnection();
        //3.构造sql
        //String sql = "insert into student values(1, '张三')";
        //String sql = "delete from student where id = 1";
        //String sql = "update student set name = '李四' where id = 1";
        //手动输入  不建议这么写  不优雅  不安全  有另外一种写法
        //String sql = "insert into student values(" + id + ", '" + name + "')";
        //手动输入  另外一种写法  使用？作为占位符
        //String sql = "insert into student values(?, ?)";
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        //statement.setInt(1,id);//setxxx方法 替换的值是int就使用setint  替换的是String就使用setString
        //statement.setString(2,name);//第一个参数是数字 表示当前要替换第几个问号  第二个参数是要替换的内容

        //4.把sql发给服务器  返回值是一个整数，表示影响到的行数
        //int n = statement.executeUpdate();
        //System.out.println(" n= " + n);
        //4.执行sql  返回ResultSet 结果集合
        ResultSet resultSet = statement.executeQuery();

        //5.遍历结果集合
        //通过next方法可以获得临时表中的每一行数据
        while(resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = "+ id + ", name = " + name);
        }
        //6.释放资源
        resultSet.close();
        statement.close();
        connection.close();

        //5.释放资源  关闭连接  释放顺序  后获取到的资源，先释放
        //statement.close();
        //connection.close();
    }
}
